package com.bwie.orders.service.impl;



import com.alibaba.fastjson2.JSONObject;
import com.bwie.common.core.domain.Result;
import com.bwie.common.core.utils.StringUtils;
import com.bwie.common.redis.service.RedisService;
import com.bwie.common.security.utils.SecurityUtils;
import com.bwie.orders.domain.OrderMessage;
import com.bwie.orders.domain.dto.OrderAddDTO;
import com.bwie.orders.domain.po.SkuPo;
import com.bwie.orders.mapper.OrderMapper;
import com.bwie.orders.service.OrderService;
import com.bwie.system.api.model.LoginUser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    @Qualifier(value = "lua-inventory-num")
    private RedisScript<Long> luaInventoryNum;

    /**
     * 生成订单
     *
     * @param orderAddDTO
     */
    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //lua脚本检验sku库存
        //获取redisTemplate
        RedisTemplate redisTemplate = redisService.redisTemplate;
        //获取sku列表
        List<SkuPo> skus = orderAddDTO.getSkus();
        //创建对象
        ArrayList<String> keys = new ArrayList<>();
        List<Integer> SkuNums = new ArrayList<>();
        //循环
        skus.forEach(skuPo -> {
            //添加
            keys.add(skuPo.getSkuId().toString());
            SkuNums.add(skuPo.getCount());
        });

        //执行lua脚本
        Long result = (Long) redisTemplate.execute(luaInventoryNum, keys, SkuNums.toArray());
        //判断lua脚本是否执行成功
        if (result == 1) {
            throw new RuntimeException( "库存不足");
        }
        //获取登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //生成一个随机的六位数订单编号
        int i = new Random().nextInt(900000) + 100000;
        //拼接订单号
        String orderNum = "DD" + i;
        //封装消息
        OrderMessage message = new OrderMessage(loginUser.getUserid(), orderAddDTO.getTotalPrice(), orderNum, orderAddDTO.getSkus());
        // 使用RabbitTemplate发送订单信息到指定交换机和路由键
        rabbitTemplate.convertAndSend("order_exchange", "order_routing_key", message);
        redisService.setCacheObject("DD:"+loginUser.getUserid(), JSONObject.toJSONString(message), 10L, TimeUnit.HOURS);
    }




    /**
     * 根据用户订单查询状态
     * @return
     */
    @Override
    public int selectOrderByRedis() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Object cacheObject = redisService.getCacheObject("DD:" + loginUser.getUserid());
        if (cacheObject!=null) {
            return 1;
        }

        return 0;


    }

//    //获取用户信息
//    LoginUser loginUser = SecurityUtils.getLoginUser();
//    //根据用户查询订单
//    String orderMessage = redisService.getCacheObject("OrderList:" + loginUser.getUserid());
//    //Jackson 库中的一个核心类，用于处理 JSON 数据的序列化（将 Java 对象转换为 JSON 字符串）和反序列化（将 JSON 字符串转换为 Java 对象）象
//    ObjectMapper objectMapper = new ObjectMapper();
//    OrderMessage order = null;
//        try {
//        order = objectMapper.readValue(orderMessage, OrderMessage.class);
//    } catch (JsonProcessingException e) {
//        throw new RuntimeException(e);
//    }
//
//    //判断用户有没有订单
//        if (StringUtils.isNull(order)) {
//        throw new RuntimeException("没有订单");
//    }
//
//       return Result.success();
}
